//
//  OptionalViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/27.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "OptionalViewController.h"
#import "OptionalView.h"
#import "OptionalTableViewCell.h"
#import "OptionalHeaderView.h"
#import "AddViewController.h"
#import <SocketRocket.h>
#import "OptionalModel.h"
#import "HomeViewController.h"
#import "BlackNavViewController.h"
#import "AppDelegate.h"
#import "LoginViewController.h"


@interface OptionalViewController ()<UITableViewDelegate,UITableViewDataSource,SRWebSocketDelegate>

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, strong)OptionalTableViewCell * optionalCell;

@property (nonatomic, strong)UIButton * rightButton;

@property (nonatomic, strong)SRWebSocket * webSocket;

@property (nonatomic, strong)NSArray * listArray;

@property (nonatomic, strong)NSMutableArray<OptionalModel *>* listModelArray;

@property (nonatomic, strong)NSString * nameString;

@end

@implementation OptionalViewController


- (void)setListModelArray:(NSMutableArray<OptionalModel *> *)listModelArray{
    
    _listModelArray = listModelArray;
    
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    
   NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * userID = [userDefaults objectForKey:@"userId"];
    
//    NSLog(@"==%@",userID);
    
    
    if (userID) {
        
//        NSString * userID = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"userId"]];
//        NSString * lastLoginTimeStr = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"lastLoginTime"]];
//        NSString * createTimeStr = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"createTime"]];
//        
//        NSLog(@"==%@",userID);
//        NSLog(@"==%@",lastLoginTimeStr);
//        NSLog(@"==%@",createTimeStr);
        
        [self loadData];
    }else{
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
        
        appDelegate.window.rootViewController = navVC;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
//    [self loadData];
    [self setupNavBar];
    [self setupUI];
}





- (void)loadData{
    
    [OptionalModel optionalWithSucess:^(NSArray<OptionalModel *> *array) {
        
        self.listModelArray = [NSMutableArray array];
        
        [self.listModelArray addObjectsFromArray:array];
        
    } error:^{
        NSLog(@"productList error");
    }];
    
    _webSocket.delegate = nil;
    [_webSocket close];
    
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://103.20.249.35:9506"]]];
    
    
    _webSocket.delegate = self;
    [_webSocket open];
}


- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
//    NSLog(@"Websocket Connected");
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
//    NSLog(@":( Websocket Failed With Error %@", error);
    
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
{
    
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    self.listArray = dic[@"quote"];
    
//    NSLog(@"%@",array);
    
    [self.tableView reloadData];
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
//    NSLog(@"====WebSocket closed");
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
//    NSLog(@"Websocket received pong");
}


- (void)setupNavBar{
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 65 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"编辑"] forState:UIControlStateNormal];
    [backButton setTitle:@" 编辑" forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13 * SCREENH6];
    [backButton setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(didCompileButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
    self.rightButton = [[UIButton alloc] init];
    
    self.rightButton.frame = CGRectMake(0 , 0 , 65 * SCREENH6, 20 * SCREENH6);
    [self.rightButton setImage:[UIImage imageNamed:@"自选-添加"] forState:UIControlStateNormal];
    [self.rightButton setTitle:@" 添加" forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13 * SCREENH6];
    [self.rightButton setTitleColor:ColorWithRGB(0xc8c8c8) forState:UIControlStateNormal];
    self.rightButton.titleLabel.textAlignment = NSTextAlignmentRight;
    
    [self.rightButton addTarget:self action:@selector(didOptionalAddButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * nextButton = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem = nextButton;
}




- (void)setupUI{
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    OptionalView * backView = [[OptionalView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:backView];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];

//    self.tableView.contentSize = [self.tableView sizeThatFits:CGSizeMake(CGRectGetWidth(self.tableView.bounds), CGFLOAT_MAX)];
    [self.tableView registerClass:[OptionalHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    self.tableView.sectionHeaderHeight = 45 * SCREENH6;
//    最后一行cell显示
    [self.tableView setFrame: CGRectMake(self.tableView.frame.origin.x , self.tableView.frame.origin.y , self.tableView.frame.size.width , self.tableView.frame.size.height-120)];
     
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    self.tableView.bounces = NO;
    
    [self.tableView registerClass:[OptionalTableViewCell class] forCellReuseIdentifier:@"OptionalCell"];
    
    [self.view addSubview:self.tableView];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.listModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.optionalCell = [tableView dequeueReusableCellWithIdentifier:@"OptionalCell" forIndexPath:indexPath];
    
    OptionalModel * model = self.listModelArray[indexPath.row];
    
    self.optionalCell.model = model;
    
    for (NSDictionary * dic in self.listArray) {
        
        if ([self.optionalCell.englishLabel.text isEqualToString:dic[@"symbol"]]) {
            
            NSString * bidStr = [NSString stringWithFormat:@"%@",dic[@"bid"]];
            
            if (self.optionalCell.reduceLabel.text) {
                
                float oldFloatString = [self.optionalCell.reduceLabel.text floatValue];
                float newFloatString = [bidStr floatValue];
                
                if (oldFloatString < newFloatString) {
                    
                    self.optionalCell.reduceLabel.backgroundColor = RED_COLOR;
                    self.optionalCell.addLabel.backgroundColor = RED_COLOR;
                }else if (oldFloatString > newFloatString){
                    
                    self.optionalCell.reduceLabel.backgroundColor = GREEN_COLOR;
                    self.optionalCell.addLabel.backgroundColor = GREEN_COLOR;
                    
                }
            }else{
                
                self.optionalCell.reduceLabel.backgroundColor = RED_COLOR;
                self.optionalCell.addLabel.backgroundColor = RED_COLOR;
            }
            
            
            self.optionalCell.reduceLabel.text = bidStr;//@"1.11846";
            self.optionalCell.addLabel.text = [NSString stringWithFormat:@"%@",dic[@"ask"]];//@"1.11855";
        }
    }
    
    return self.optionalCell;
}


//设置是否可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}


- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}



//设置处理编辑情况
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        
        self.optionalCell = [tableView cellForRowAtIndexPath:indexPath];
        
        NSString * string = [NSString stringWithFormat:@"%@",self.optionalCell.englishLabel.text];
        
        NSDictionary * parameters = @{@"symbolId":string};
        
        [[NetworkTool sharedTools] POST:@"symbols/delete-optional" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
        //更新数据
        [self.listModelArray removeObjectAtIndex:indexPath.row];
        //更新UI
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }else if (editingStyle == UITableViewCellEditingStyleInsert) {
        
    }
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    OptionalHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    
    return header;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 73 * SCREENH6;
    
}


//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
////    tableView.editingStyle =UITableViewCellEditingStyleDelete
//    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
////    UITableViewCellEditingStyleDelete;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.optionalCell = [tableView cellForRowAtIndexPath:indexPath];
    
    self.nameString = self.optionalCell.englishLabel.text;
    NSString * chineseName = self.optionalCell.chineseLabel.text;
    
    NSString * name = [NSString stringWithFormat:@"%@(%@)",chineseName,self.nameString];
    
    NSString * sellString;
    NSString * buyString;
    
    if (self.optionalCell.reduceLabel.text.length <= 7) {
        sellString = self.optionalCell.reduceLabel.text;
    }else{
        sellString = [self.optionalCell.reduceLabel.text substringToIndex:8];
    }
    
    if (self.optionalCell.addLabel.text.length <= 7) {
        buyString = self.optionalCell.addLabel.text;
    }else{
        buyString = [self.optionalCell.addLabel.text substringToIndex:8];
    }
    
    NSDictionary *dic = @{@"titleName":name,@"sellString":sellString,@"buyString":buyString,@"requsetString":self.nameString};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"titleName" object:@"titleString" userInfo:dic];
    
    self.tabBarController.selectedIndex = 0;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        return UITableViewCellEditingStyleDelete;
    
}

//点击编辑按钮
- (void)didCompileButton:(UIButton *)button{
    
    //进入编辑状态
   
    if (self.tableView.editing) {
        [self loadData];
        [self.tableView setEditing:NO animated:NO];
        
        self.rightButton.hidden = NO;
        
        [button setImage:[UIImage imageNamed:@"编辑"] forState:UIControlStateNormal];
        [button setTitle:@" 编辑" forState:UIControlStateNormal];
        
    }else{
        [_webSocket close];
        [self.tableView setEditing:YES animated:YES];
        
        self.rightButton.hidden = YES;
        
        [button setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [button setTitle:@"完成" forState:UIControlStateNormal];
        
    }
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"showOrHiddenLabel" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showOrHiddenHeaderLabel" object:nil];
    
//    [self.tableView reloadData];
}


//点击添加按钮
- (void)didOptionalAddButton{
    
    self.hidesBottomBarWhenPushed = YES;
    
    AddViewController * addVC = [AddViewController new];
    
    [self.navigationController pushViewController:addVC animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}



- (void)viewDidDisappear:(BOOL)animated{
    
    [_webSocket close];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
